package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.commen.BaseContext;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("新增菜品和菜品口味信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dishDto", value = "菜品综合信息Dto", required = true),
            @ApiImplicitParam(name = "request", value = "请求变量", required = true)
    })
    @PostMapping
    public R<String> saveDishAndDishFlavor(@RequestBody DishDto dishDto, HttpServletRequest request) {
        Long empID = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empID);
        dishService.saveWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("添加成功..");
    }

    @ApiOperation("分页查询接口")
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true),
            @ApiImplicitParam(name = "name", value = "菜品名称", required = false)
    })
    public R<Page> selectPage(Integer page, Integer pageSize, String name) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        dishService.page(pageInfo, lqw);

        //前端需要的数据必须用这种数据类型接收
        Page<DishDto> dishDtoPage = new Page<>();
        //将pageInfo中的所有数据拷贝到dishDtoPage,PageInfo中的记录数据信息缺少菜品名称不完整所以不必拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        //先得到pageInfo中所有的菜品数据
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtos = records.stream().map(item -> {
            //获取records中每一条数据中的菜品ID
            Long categoryId = item.getCategoryId();
            //通过ID获取对应的菜品数据
            Category category = categoryService.getById(categoryId);
            //通过菜品数据获得对应的菜品名称(上面dishDtoPage中需要的)
            String categoryName = category.getName();
            //将菜品名称存放到DishDto类型的数据中，(因为Dish类型无法接收这个数据)
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            //将Dish类型的数据item存放到DishDto类型的数据中
            BeanUtils.copyProperties(item, dishDto);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    @ApiOperation("菜品信息查询接口")
    @GetMapping("/{id}")
    public R<DishDto> selectDishDto(@PathVariable Long id) {
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(lqw);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @ApiOperation("更新菜品接口")
    @PutMapping
    public R<String> updateWithFlavor(@RequestBody DishDto dishDto, HttpServletRequest request) {
        dishService.updateWithFlavor(dishDto, request);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改成功..");
    }

    @ApiOperation("删除菜品接口")
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        log.info(ids.toString());
        dishService.removeByIds(ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功..");
    }

    @ApiOperation("修改状态接口")
    @PostMapping("/status/{status}")
    public R<String> editStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        dishService.editStatus(status, ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("操作成功..");
    }

    @ApiOperation("菜品信息查询接口")
    @GetMapping("/list")
    public R<List<DishDto>> dishList(Dish dish) {
        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(lqw);
        log.info(list.toString());

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
